// pages/admin/rescue-review/rescue-review.js
const { get, put } = require('../../../utils/request')
const { formatDate, showSuccess, showError, showConfirm, getImageUrl } = require('../../../utils/util')

Page({
  data: {
    applicationId: null,
    applicationInfo: {},
    handleAction: '', // 'processing' 或 'completed'
    handleNote: '',
    submitting: false,
    loading: true
  },

  onLoad(options) {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    if (options.id) {
      this.setData({
        applicationId: options.id
      })
      this.loadApplicationDetail()
    } else {
      showError('参数错误')
      wx.navigateBack()
    }
  },

  // 加载申请详情
  loadApplicationDetail() {
    this.setData({ loading: true })

    get(`/rescue/${this.data.applicationId}`).then(res => {
      const applicationInfo = res.data

      // 格式化时间
      applicationInfo.createTime = formatDate(applicationInfo.createTime)
      if (applicationInfo.handleTime) {
        applicationInfo.handleTime = formatDate(applicationInfo.handleTime)
      }

      // 处理图片
      if (applicationInfo.images) {
        const images = applicationInfo.images.split(',').filter(img => img.trim())
        applicationInfo.imageList = images.map(img => getImageUrl(img.trim()))
      } else {
        applicationInfo.imageList = []
      }

      this.setData({
        applicationInfo
      })

      // 设置页面标题
      wx.setNavigationBarTitle({
        title: `处理救助 - ${applicationInfo.petType}`
      })

    }).catch(err => {
      showError('加载申请信息失败')
      wx.navigateBack()
    }).finally(() => {
      this.setData({ loading: false })
    })
  },

  // 选择处理动作
  selectAction(e) {
    const action = e.currentTarget.dataset.action
    // 如果当前状态是"处理中"，只允许选择"completed"动作
    if (this.data.applicationInfo.status === '处理中' && action !== 'completed') {
      showError('处理中的申请只能标记为完成')
      return
    }
    this.setData({
      handleAction: action
    })
  },

  // 处理备注输入
  onNoteInput(e) {
    this.setData({
      handleNote: e.detail.value
    })
  },

  // 预览图片
  previewImage(e) {
    const current = e.currentTarget.dataset.current
    const urls = e.currentTarget.dataset.urls

    wx.previewImage({
      current,
      urls
    })
  },

  // 表单验证
  validateForm() {
    if (!this.data.handleAction) {
      showError('请选择处理动作')
      return false
    }

    if (this.data.handleNote.length === 0) {
      showError('请填写处理备注')
      return false
    }

    const trimmedNote = this.data.handleNote.trim()
    if (trimmedNote.length < 5) {
      showError('处理备注至少需要5个字符')
      return false
    }

    return true
  },

  // 提交处理
  async onSubmit() {
    if (this.data.submitting) return

    if (!this.validateForm()) return

    const actionText = this.data.handleAction === 'processing' ? '开始处理' : '标记完成'

    try {
      await showConfirm(`确定要${actionText}这个救助申请吗？`)
    } catch {
      return
    }

    this.setData({ submitting: true })

    const status = this.data.handleAction === 'processing' ? '处理中' : '已完成'
    const handleNote = this.data.handleNote.trim()

    // 使用专门的处理接口，传递查询参数
    const handleUrl = `/rescue/handle/${this.data.applicationId}?status=${encodeURIComponent(status)}&handleNote=${encodeURIComponent(handleNote)}`

    put(handleUrl).then(res => {
      showSuccess(`${actionText}成功`)

      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)

    }).catch(err => {
      showError(err.msg || '处理失败，请重试')
    }).finally(() => {
      this.setData({ submitting: false })
    })
  },

  // 取消
  onCancel() {
    wx.navigateBack()
  }
})
